package com.atcd.sotoken.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.*;

@Component
@Slf4j
public class ConfigFileWatcher {


    @Value("${server.port}")
    private String port;

    @Value("${management.endpoints.web.exposure.include}")
    private String endpoint;

//    监听的config目录
    @Value("${myconfig.listenDir}")
    private  String watchDirectory ;


    public void startWatching() throws IOException, InterruptedException {
        log.info("我配置文件的监听目录为: "+watchDirectory);
        Path path = Paths.get(watchDirectory).toAbsolutePath().normalize();
        
        if (!Files.exists(path)) {
            System.err.println("监听目录不存在: " + path);
            return;
        }

        WatchService watchService = FileSystems.getDefault().newWatchService();
        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

        System.out.println("开始监听目录: " + path);
        
        new Thread(() -> {
            try {
                while (true) {
                    WatchKey key = watchService.take();
                    for (WatchEvent<?> event : key.pollEvents()) {
                        handleFileEvent(event);
                    }
                    key.reset();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }

    private void handleFileEvent(WatchEvent<?> event) {
        Path changedFile = (Path) event.context();
        
        if (changedFile.toString().endsWith(".yml") || 
            changedFile.toString().endsWith(".properties")) {
            
            System.out.println("检测到配置文件变更: " + changedFile);
            triggerRefresh();
        }
    }

    private void triggerRefresh() {
        String url = "http://127.0.0.1:" + port + "/actuator/"+endpoint;
        try {
            String os = System.getProperty("os.name").toLowerCase();
            ProcessBuilder processBuilder = new ProcessBuilder();
            
            if (os.contains("win")) {
                processBuilder.command("cmd.exe", "/c", "curl", "-X", "POST", url);
            } else {
                processBuilder.command("curl", "-X", "POST", url);
            }
            
            Process process = processBuilder.start();
            int exitCode = process.waitFor();
            
            if (exitCode == 0) {
                System.out.println("配置刷新成功");
            } else {
                System.err.println("刷新失败，退出码: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            System.err.println("执行刷新命令失败: " + e.getMessage());
        }
    }
}